package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.vo.PromotionVoDetail;
import com.jsh.erp.datasource.vo.Replenishment;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.materialCategory.MaterialCategoryService;
import com.jsh.erp.service.promotionHead.PromotionHeadService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.unit.UnitService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * @author ji|sheng|hua jshERP
 */
@RestController
@RequestMapping(value = "/material")
@Api(tags = {"商品管理"})
public class MaterialController {
    private Logger logger = LoggerFactory.getLogger(MaterialController.class);

    @Resource
    private MaterialService materialService;

    @Resource
    private DepotItemService depotItemService;

    @Resource
    private UnitService unitService;

    @Resource
    private DepotService depotService;

    @Resource
    private PromotionHeadService promotionHeadService;

    @Resource
    private RedisService redisService;

    @Resource
    private SupplierService supplierService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private MaterialCategoryService materialCategoryService;

    /**
     * 检查商品是否存在
     * @param id
     * @param name
     * @param model
     * @param color
     * @param standard
     * @param mfrs
     * @param otherField1
     * @param otherField2
     * @param otherField3
     * @param unit
     * @param unitId
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/checkIsExist")
    @ApiOperation(value = "检查商品是否存在")
    public String checkIsExist(@RequestParam("id") String id, @RequestParam("name") String name,
                               @RequestParam("model") String model, @RequestParam("color") String color,
                               @RequestParam("standard") String standard, @RequestParam("mfrs") String mfrs,
                               @RequestParam("otherField1") String otherField1, @RequestParam("otherField2") String otherField2,
                               @RequestParam("otherField3") String otherField3, @RequestParam("unit") String unit,@RequestParam("unitId") String unitId,
                               HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String lanCode = redisService.getLanCodeFromSession(request);
        int exist = materialService.checkIsExist(id, name, StringUtil.toNull(model), StringUtil.toNull(color),
                StringUtil.toNull(standard), StringUtil.toNull(mfrs), StringUtil.toNull(otherField1),
                StringUtil.toNull(otherField2), StringUtil.toNull(otherField3), StringUtil.toNull(unit), unitId);
        if(exist > 0) {
            objectMap.put("status", true);
        } else {
            objectMap.put("status", false);
        }
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }
    @GetMapping(value = "/checkMaterialNameIsExist")
    @ApiOperation(value = "检查商品名称是否存在")
    public String checkMaterialNameIsExist( @RequestParam("name") String name,
                                            @RequestParam("id") String id,
                                            @RequestParam("standard") String standard,
                               HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String lanCode = redisService.getLanCodeFromSession(request);
        int exist = materialService.checkMaterialNameIsExist(name,id,standard);
        if(exist > 0) {
            objectMap.put("status", true);
        } else {
            objectMap.put("status", false);
        }
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }
    /**
     * 批量设置状态-启用或者禁用
     * @param jsonObject
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/batchSetStatus")
    @ApiOperation(value = "批量设置状态-启用或者禁用")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request)throws Exception {
        Boolean status = jsonObject.getBoolean("status");
        String ids = jsonObject.getString("ids");
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        int res = materialService.batchSetStatus(status, ids);
        if(res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/batchUpdateSalesPrice")
    @ApiOperation(value = "批量更新确认售价-启用或者禁用（针对销售）")
    public String batchUpdateSalesPrice(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String enableBatchNumber = jsonObject.getString("enableBatchNumber");
        String ids = jsonObject.getString("ids");
        String lanCode = redisService.getLanCodeFromSession(request);
        int res = materialService.batchUpdateSalesPrice(enableBatchNumber, ids);
        if(res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    /**
     * 根据id来查询商品名称
     * @param id
     * @param request
     * @return
     */
    @GetMapping(value = "/findById")
    @ApiOperation(value = "根据id来查询商品名称")
    public BaseResponseInfo findById(@RequestParam("id") String id, HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<MaterialVo4Unit> list = materialService.findById(id);
            res.code = 200;
            res.data = list;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 根据meId来查询商品名称
     * @param meId
     * @param request
     * @return
     */
    @GetMapping(value = "/findByIdWithBarCode")
    @ApiOperation(value = "根据meId来查询商品名称")
    public BaseResponseInfo findByIdWithBarCode(@RequestParam("meId") String meId,
                                                @RequestParam("mpList") String mpList,
                                                HttpServletRequest request) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            String[] mpArr = mpList.split(",");
            MaterialVo4Unit mu = new MaterialVo4Unit();
            List<MaterialVo4Unit> list = materialService.findByIdWithMeId(meId);
            if(list!=null && list.size()>0) {
                mu = list.get(0);
                mu.setMaterialOther(materialService.getMaterialOtherByParam(mpArr, mu));
            }
            res.code = 200;
            res.data = mu;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 查找商品信息-下拉框
     * @param mpList
     * @param request
     * @return
     */
    @GetMapping(value = "/findBySelect")
    @ApiOperation(value = "查找商品信息")
    public JSONObject findBySelect(@RequestParam(value = "categoryId", required = false) String categoryId,
                                  @RequestParam(value = "q", required = false) String q,
                                  @RequestParam("mpList") String mpList,
                                  @RequestParam(value = "depotId", required = false) String depotId,
                                  @RequestParam(value = "enableSerialNumber", required = false) String enableSerialNumber,
                                  @RequestParam(value = "enableBatchNumber", required = false) String enableBatchNumber,
                                  @RequestParam("page") Integer currentPage,
                                  @RequestParam("rows") Integer pageSize,
                                  @RequestParam(value = "organId", required = false) String organId,
                                  @RequestParam(value = "color", required = false) String color,
                                  HttpServletRequest request) throws Exception{
        JSONObject object = new JSONObject();
        try {
            List<MaterialVo4Unit> dataList = materialService.findBySelectWithBarCode(categoryId, q, enableSerialNumber,
                    enableBatchNumber, (currentPage-1)*pageSize, pageSize,organId,color);
            String[] mpArr = mpList.split(",");
            int total = materialService.findBySelectWithBarCodeCount(categoryId, q, enableSerialNumber,
                    enableBatchNumber,organId,color);
            object.put("total", total);
            JSONArray dataArray = new JSONArray();
            //存放数据json数组
            if (null != dataList && dataList.size()>0) {
                Map<String,BigDecimal> currentStockMap = materialService.getCurrentStockMapByMaterialList(dataList,depotId);
                for (MaterialVo4Unit material : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", material.getId()); //商品扩展表的id
                    item.put("mBarCode", material.getmBarCode());
                    item.put("name", material.getName());
                    item.put("categoryName", material.getCategoryName());
                    item.put("standard", material.getStandard());
                    item.put("model", material.getModel());
                    item.put("color", material.getColor());
                    item.put("unit", material.getCommodityUnit() );
                    item.put("unitName", material.getUnitName());
                    item.put("sku", material.getSku());
                    item.put("enableSerialNumber", material.getEnableSerialNumber());
                    item.put("enableBatchNumber", material.getEnableBatchNumber());
                    BigDecimal stock= currentStockMap.get(material.getId())!=null? currentStockMap.get(material.getId()): BigDecimal.ZERO;
//                    if(StringUtil.isNotEmpty(material.getSku())){
//                        stock = depotItemService.getSkuStockByParam(depotId,material.getMeId(),null,null);
//                    } else {
//                        stock = depotItemService.getStockByParam(depotId,material.getId(),null,null);
//                        if (material.getUnitId()!=null){
//                            String commodityUnit = material.getCommodityUnit();
//                            stock = unitService.parseStockByUnit(stock, unit, commodityUnit);
//                        }
//                    }
//                    StringBuffer str = new StringBuffer();
                    item.put("stock", stock);
//                    if(null!= unit.getOtherUnit() && StringUtils.isNotEmpty(unit.getOtherUnit()) && null!= unit.getRatio() && unit.getRatio() != 0) {
//                        str.append("(" +stock.divide(BigDecimal.valueOf(unit.getRatio()),2,BigDecimal.ROUND_HALF_UP)+unit.getOtherUnit()+")");
//                    }
//                    if (null!= unit.getOtherUnitTwo() && StringUtils.isNotEmpty(unit.getOtherUnitTwo()) && null!= unit.getRatioTwo() && unit.getRatioTwo() != 0) {
//                        str.append("/(" +stock.divide(BigDecimal.valueOf(unit.getRatioTwo()),2,BigDecimal.ROUND_HALF_UP)+unit.getOtherUnitTwo()+")");
//                    }
//                    item.put("assistStock", str.toString());
                    item.put("supplier", material.getSupplier());
//                    item.put("expand", materialService.getMaterialOtherByParam(mpArr, material));
                    dataArray.add(item);
                }
            }
            object.put("rows", dataArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 根据商品id查找商品信息
     * @param meId
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaterialByMeId")
    @ApiOperation(value = "根据商品id查找商品信息")
    public JSONObject getMaterialByMeId(@RequestParam(value = "meId", required = false) String meId,
                                        @RequestParam("mpList") String mpList,
                                        HttpServletRequest request) throws Exception{
        JSONObject item = new JSONObject();
        try {
            String[] mpArr = mpList.split(",");
            List<MaterialVo4Unit> materialList = materialService.getMaterialByMeId(meId);
            if(materialList!=null && materialList.size()!=1) {
                return item;
            } else if(materialList.size() == 1) {
                MaterialVo4Unit material = materialList.get(0);
                item.put("Id", material.getMeId()); //商品扩展表的id
                String ratio; //比例
                if (material.getUnitId() == null || material.getUnitId().equals("")) {
                    ratio = "";
                } else {
                    ratio = material.getUnitName();
                    ratio = ratio.substring(ratio.indexOf("("));
                }
                //名称/型号/扩展信息/包装
                String MaterialName = "";
                MaterialName = MaterialName + material.getmBarCode() + "_" + material.getName()
                        + ((material.getStandard() == null || material.getStandard().equals("")) ? "" : "(" + material.getStandard() + ")");
                String expand = materialService.getMaterialOtherByParam(mpArr, material); //扩展信息
                MaterialName = MaterialName + expand + ((material.getUnit() == null || material.getUnit().equals("")) ? "" : "(" + material.getUnit() + ")") + ratio;
                item.put("MaterialName", MaterialName);
                item.put("name", material.getName());
                item.put("expand", expand);
                item.put("model", material.getModel());
                item.put("standard", material.getStandard());
                item.put("unit", material.getUnit() + ratio);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return item;
    }

    /**
     * 生成excel表格
     * @param categoryId
     * @param name
     * @param barCode
     * @param standard
     * @param color
     * @param expiryNum
     * @param enabled
     * @param enableSerialNumber
     * @param enableBatchNumber
     * @param remark
     * @param mpList
     * @param request
     * @param response
     */
//    @GetMapping(value = "/exportExcel")
//    @ApiOperation(value = "生成excel表格")
//    public void exportExcel(@RequestParam(value = "categoryId", required = false) String categoryId,
//                            @RequestParam(value = "materialParam", required = false) String materialParam,
//                            @RequestParam(value = "color", required = false) String color,
//                            @RequestParam(value = "weight", required = false) String weight,
//                            @RequestParam(value = "expiryNum", required = false) String expiryNum,
//                            @RequestParam(value = "enabled", required = false) String enabled,
//                            @RequestParam(value = "enableSerialNumber", required = false) String enableSerialNumber,
//                            @RequestParam(value = "enableBatchNumber", required = false) String enableBatchNumber,
//                            @RequestParam(value = "remark", required = false) String remark,
//                            @RequestParam(value = "mpList", required = false) String mpList,
//                            HttpServletRequest request, HttpServletResponse response) {
//        try {
//            String[] mpArr = new String[]{};
//            if(StringUtil.isNotEmpty(mpList)){
//                mpArr= mpList.split(",");
//            }
//            List<MaterialVo4Unit> dataList = materialService.exportExcel(StringUtil.toNull(materialParam), StringUtil.toNull(color),
//                    StringUtil.toNull(weight), StringUtil.toNull(expiryNum), StringUtil.toNull(enabled), StringUtil.toNull(enableSerialNumber),
//                    StringUtil.toNull(enableBatchNumber), StringUtil.toNull(remark), StringUtil.toNull(categoryId));
////            String[] names = {"条码", "名称", "规格", "型号", "颜色", "类别", "扩展信息", "单位", "基础重量", "保质期", "采购价", "零售价", "销售价", "最低售价", "备注", "状态", "序列号", "批号"};
//            String[] names = {"条码", "名称", "规格", "型号",  "类别", "扩展信息", "单位", "保质期", "采购价", "零售价", "一级批发价", "最低售价", "备注", "状态", "批号"};
//            String title = "商品信息";
//            List<String[]> objects = new ArrayList<>();
//            if (null != dataList) {
//                for (MaterialVo4Unit m : dataList) {
//                    String[] objs = new String[100];
//                    objs[0] = m.getmBarCode();
//                    objs[1] = m.getName();
//                    objs[2] = m.getStandard();
//                    objs[3] = m.getModel();
////                    objs[4] = m.getColor();
//                    objs[4] = m.getCategoryName();
//                    objs[5] = materialService.getMaterialOtherByParam(mpArr, m);
//                    objs[6] = m.getCommodityUnit();
////                    objs[8] = m.getWeight() == null? "" : m.getWeight().toString();
//                    objs[7] = m.getExpiryNum() == null? "" : m.getExpiryNum().toString();
//                    objs[8] = m.getPurchaseDecimal() == null? "" : m.getPurchaseDecimal().toString();
//                    objs[9] = m.getCommodityDecimal() == null? "" : m.getCommodityDecimal().toString();
//                    objs[10] = m.getWholesaleDecimal() == null? "" : m.getWholesaleDecimal().toString();
//                    objs[11] = m.getLowDecimal() == null? "" : m.getLowDecimal().toString();
//                    objs[12] = m.getRemark();
//                    objs[13] = m.getEnabled() ? "启用" : "禁用";
////                    objs[14] = "1".equals(m.getEnableSerialNumber()) ? "有" : "无";
//                    objs[14] = "1".equals(m.getEnableBatchNumber()) ? "有" : "无";
//                    objects.add(objs);
//                }
//            }
//            File file = ExcelUtils.exportObjectsWithoutTitle(title, names, title, objects);
//            ExportExecUtil.showExec(file, file.getName(), response);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    @GetMapping(value = "/exportExcel")
    @ApiOperation(value = "生成excel表格")
    public void exportExcel(@RequestParam(value = "categoryId", required = false) String categoryId,
                            @RequestParam(value = "materialParam", required = false) String name,
                            @RequestParam(value = "materialParam", required = false) String barCode,
                            @RequestParam(value = "materialParam", required = false) String standard,
                            @RequestParam(value = "materialParam", required = false) String model,
                            @RequestParam(value = "materialParam", required = false) String color,
                            @RequestParam(value = "expiryNum", required = false) String expiryNum,
                            @RequestParam(value = "enabled", required = false) String enabled,
                            @RequestParam(value = "enableSerialNumber", required = false) String enableSerialNumber,
                            @RequestParam(value = "enableBatchNumber", required = false) String enableBatchNumber,
                            @RequestParam(value = "remark", required = false) String remark,
                            @RequestParam(value = "mpList", required = false) String mpList,
                            @RequestParam(value = "selections", required = false) String selections,
                            HttpServletRequest request, HttpServletResponse response) {
        try {
            List<String> materialIdList =new ArrayList<String>();
            if (StringUtils.isNotEmpty(selections)){
                materialIdList = StringUtil.strToStringList(selections);
            }
            String lanCode = redisService.getLanCodeFromSession(request);
            List<MaterialVo4Unit> dataList = materialService.exportExcel(StringUtil.toNull(name),StringUtil.toNull(barCode),StringUtil.toNull(standard),StringUtil.toNull(model),StringUtil.toNull(color), StringUtil.toNull(expiryNum), StringUtil.toNull(enabled), StringUtil.toNull(enableSerialNumber),
                    StringUtil.toNull(enableBatchNumber), StringUtil.toNull(remark), StringUtil.toNull(categoryId),materialIdList);
            String[] zhName = {"货号", "分类", "商品名称", "规格",  "供应商", "单位", "商品条码", "商品编号","比例", "采购价", "零售价","销售价","是否称重 0-否 1-是","状态 0-不启用 1-启用"};
            String[] enName = {"Stock Item", "Group", "Description", "specification",  "Supplier", "unit", "barCode", "code","ratio", "Cost", "retail", "RRP", "Whether the goods are weighed (no-0;yes-1)","status（no-0;yes-1)"};
            String zhTitle = "商品信息";
            String enTitle = "Commodity information";
            List<Object[]> objects = new ArrayList<>();
            Map<String,List<Object[]>> object = new HashMap<>();
            Set<String> parentNameList=new HashSet<>();
            if (null != dataList) {
                Map<String, List<MaterialVo4Unit>> map = dataList.stream().collect(Collectors.groupingBy(MaterialVo4Unit::getParentName));
                parentNameList = map.keySet();
                for (String parentName : parentNameList) {
                    List<MaterialVo4Unit> detailList = map.get(parentName);
                    for (MaterialVo4Unit m : detailList) {
                        Object[] objs = new Object[100];
                        objs[0] = m.getColor();
                        objs[1] = m.getCategoryName();
                        objs[2] = m.getName();
                        objs[3] = m.getStandard();
                        objs[4] = m.getSupplier();
                        objs[5] = m.getUnitName();
                        objs[6] = m.getBarCode();
                        objs[7] = m.getCode();
                        objs[8] = m.getRatio() ==null ? 0 :m.getRatio().toString();
                        objs[9] = m.getPurchaseDecimal() == null? 0 : m.getPurchaseDecimal().doubleValue();
                        objs[10] = m.getCommodityDecimal() == null? 0 : m.getCommodityDecimal().doubleValue();
                        objs[11] = m.getWholesaleDecimal() == null? 0 : m.getWholesaleDecimal().doubleValue();
//                    objs[12] = "1".equals(m.getMfrs()) ? "zh".equals(lanCode) ? "是" :"yes" : "zh".equals(lanCode) ? "否" :"no" ;
//                    objs[13] = m.getEnabled() ? "zh".equals(lanCode) ? "启用" :"yes" : "zh".equals(lanCode) ? "禁用" :"no" ;
                        objs[12] = m.getMfrs();
                        objs[13] = m.getEnabled() ? "1" :"0" ;
                        objects.add(objs);
                    }
                    object.put(parentName,objects);
                    objects=new ArrayList<>();
                }
            }
            File file= null;
            if ("zh".equals(lanCode)){
                file = ExcelUtils.exportObjectsWithoutListTitle(zhTitle, zhName, parentNameList, object);
            }else {
                file = ExcelUtils.exportObjectsWithoutListTitle(enTitle, enName, parentNameList, object);
            }
            ExportExecUtil.showExec(file, file.getName(), response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * excel表格导入产品（含初始库存）
     * @param file
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "excel表格导入产品")
    public BaseResponseInfo importExcel(MultipartFile file,
                            HttpServletRequest request, HttpServletResponse response) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            res = materialService.importExcel(file, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }


    @PostMapping(value = "/importOpeningInventory")
    @ApiOperation(value = "导入期初库存明细")
    public BaseResponseInfo importOpeningInventory(MultipartFile file,HttpServletRequest request, HttpServletResponse response) throws Exception{
        BaseResponseInfo res = new BaseResponseInfo();
            String fileName = file.getOriginalFilename();
            if(StringUtil.isNotEmpty(fileName)) {
                String fileExt = fileName.substring(fileName.indexOf(".")+1);
                if(!"xls".equals(fileExt)) {
                    throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_EXTENSION_ERROR_CODE,
                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_EXTENSION_ERROR_MSG : ExceptionConstants.MATERIAL_EXTENSION_ERROR_MSG_US);
                }
            }
            Workbook workbook = Workbook.getWorkbook(file.getInputStream());
            Sheet src = workbook.getSheet(0);
//            //单次导入超出1000条
//            if(src.getRows()>1002) {
//                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_IMPORT_OVER_LIMIT_CODE,
//                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_IMPORT_OVER_LIMIT_MSG : ExceptionConstants.MATERIAL_IMPORT_OVER_LIMIT_MSG_US));
//            }

//        int barCodeRepetition = ExcelUtils.checkUnique(src, 1, 2);
//        if (barCodeRepetition > 0) {
//            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NAME_REPETITION_CODE,
//                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_NAME_REPETITION_MSG : ExceptionConstants.MATERIAL_NAME_REPETITION_MSG_US, barCodeRepetition+1));
//        }
        int rowNum = 2;
        for (int num = 2; num < src.getRows(); num++) {//跳过第一行，看个人需求
            Cell[] row = src.getRow(num);
            if (row != null) rowNum++;
        }

        List<MaterialVo4Unit> mList = new ArrayList<>();
        String sheetName = src.getName();
        String parentId=null;
        if (StringUtil.isEmpty(sheetName)) {
            throw new BusinessRunTimeException(ExceptionConstants.SHEET_NAME_EMPTY_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.SHEET_NAME_EMPTY_MSG : ExceptionConstants.SHEET_NAME_EMPTY_MSG_US);

        }else {
            parentId = materialCategoryService.getCategoryIdByName(sheetName);
            if (StringUtils.isEmpty(parentId)) {
                throw new BusinessRunTimeException(ExceptionConstants.SHEET_ID_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.SHEET_ID_EMPTY_MSG : ExceptionConstants.SHEET_ID_EMPTY_MSG_US, sheetName));
            }
        }
        for (int i = 2; i < rowNum; i++) {
            String materialName = ExcelUtils.getContent(src, i, 0); //商品名称
            String categoryName = ExcelUtils.getContent(src, i, 1); //商品类别
            String standard = ExcelUtils.getContent(src, i, 2); //规格
            String color = ExcelUtils.getContent(src, i, 3); //货号
            String barCode = ExcelUtils.getContent(src, i, 4); //条码
            String unit = ExcelUtils.getContent(src, i, 5); //单位
            String number = ExcelUtils.getContent(src, i, 6); //数量

            //商品名称为空
            if (StringUtil.isEmpty(materialName)) {
                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NAME_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_NAME_EMPTY_MSG : ExceptionConstants.MATERIAL_NAME_EMPTY_MSG_US, i + 1));
            }
            if (StringUtil.isEmpty(materialName)) {
                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_NAME_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_NAME_EMPTY_MSG : ExceptionConstants.MATERIAL_NAME_EMPTY_MSG_US, i + 1));
            }
            if (StringUtil.isEmpty(unit)) {
                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_UNIT_IMPORT_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_UNIT_IMPORT_EMPTY_MSG : ExceptionConstants.MATERIAL_UNIT_IMPORT_EMPTY_MSG_US, i + 1));
            }
            //数量为空
            if (StringUtil.isEmpty(number)) {
                throw new BusinessRunTimeException(ExceptionConstants.NUMBER_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.NUMBER_EMPTY_MSG : ExceptionConstants.NUMBER_EMPTY_MSG_US, i + 1));
            }
            String categoryId = materialCategoryService.getCategoryIdByParentName(categoryName,parentId);
            if (StringUtils.isEmpty(categoryId)) {
                throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_UNIT_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MATERIAL_CATEGORY_ID_EMPTY_MSG : ExceptionConstants.MATERIAL_CATEGORY_ID_EMPTY_MSG_US,"("+sheetName+")"+(i+1)));
            }

            MaterialVo4Unit mvo = materialService.getMaterialInfoByMaterialNameWithUnit(materialName, categoryId, unit, standard, color, barCode);
            if (mvo == null) {
                throw new BusinessRunTimeException(ExceptionConstants.MVO_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.MVO_EMPTY_MSG : ExceptionConstants.MVO_EMPTY_MSG_US, i + 1));
            }
            BigDecimal operNumber = new BigDecimal(number);
            mvo.setOperNumber(operNumber);
            mvo.setMaterialId(mvo.getId());
            //数量为空
            if (mvo.getPurchaseDecimal() == null || mvo.getPurchaseDecimal().compareTo(BigDecimal.ZERO) <= 0) {
                throw new BusinessRunTimeException(ExceptionConstants.PURCHASE_PRICE_EMPTY_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.PURCHASE_PRICE_EMPTY_MSG : ExceptionConstants.PURCHASE_PRICE_EMPTY_MSG_US, i + 1));
            }
            mvo.setBillPrice(mvo.getPurchaseDecimal());
            mvo.setAllPrice(operNumber.multiply(mvo.getPurchaseDecimal()));
            mList.add(mvo);
        }
        res.code = 200;
        res.data = mList;
        return res;
    }

    public BigDecimal parseBigDecimalEx(String str)throws Exception{
        if(!StringUtil.isEmpty(str)) {
            return  new BigDecimal(str);
        } else {
            return null;
        }
    }

    /**+
     * 获取商品序列号
     * @param q
     * @param currentPage
     * @param pageSize
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaterialEnableSerialNumberList")
    @ApiOperation(value = "获取商品序列号")
    public JSONObject getMaterialEnableSerialNumberList(
                                @RequestParam(value = "q", required = false) String q,
                                @RequestParam("page") Integer currentPage,
                                @RequestParam("rows") Integer pageSize,
                                HttpServletRequest request,
                                HttpServletResponse response)throws Exception {
        JSONObject object= new JSONObject();
        try {
            List<MaterialVo4Unit> list = materialService.getMaterialEnableSerialNumberList(q, (currentPage-1)*pageSize, pageSize);
            String count = materialService.getMaterialEnableSerialNumberCount(q);
            object.put("rows", list);
            object.put("total", count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 获取最大条码
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaxBarCode")
    @ApiOperation(value = "获取最大条码")
    public BaseResponseInfo getMaxBarCode() throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        String barCode = materialService.getMaxBarCode();
        map.put("barCode", barCode);
        res.code = 200;
        res.data = map;
        return res;
    }

    /**
     * 商品名称模糊匹配
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaterialNameList")
    @ApiOperation(value = "商品名称模糊匹配")
    public JSONArray getMaterialNameList() throws Exception {
        JSONArray arr = new JSONArray();
        try {
            List<String> list = materialService.getMaterialNameList();
            for (String s : list) {
                JSONObject item = new JSONObject();
                item.put("value", s);
                item.put("text", s);
                arr.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }

    /**
     * 根据商品价格id查询商品信息
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaterialByUnit")
    @ApiOperation(value = "根据商品价格id查询商品信息")
    public BaseResponseInfo getMaterialByUnit(@RequestParam("meId")@ApiParam("商品价格id，用','号隔开") String meId,
                                          @RequestParam(value = "depotId", required = false)@ApiParam("仓库 销售时，获取促销活动价") String depotId,
                                          @RequestParam(value = "organId", required = false)@ApiParam("客户id/供应商id  销售时，获取活动价、客户等级价") String organId,
                                          @RequestParam(required = false, value = "prefixNo")@ApiParam("单据前缀，如（促销特价：'CXTJ'）") String prefixNo,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
        if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
            res.code = 500;
            res.data = "zh".equals(lanCode) ? "未设置税率" : "Untaxed rate";
            return res;
        }
        BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());
        try {
            List<MaterialVo4Unit> list = materialService.getMaterialByMeIdList(meId);
            if(list!=null && list.size()>0) {
                for(MaterialVo4Unit mvo: list) {
                    mvo.setTaxRate(taxRate);
                    if ("LSCK".equals(prefixNo) || "LSTH".equals(prefixNo)) {
                        //零售价
                        mvo.setTaxUnitPrice(mvo.getCommodityDecimal());
                        mvo.setBillPrice(mvo.getCommodityDecimal());
                    } else if ("CGDD".equals(prefixNo) || "CGRK".equals(prefixNo) || "CGTH".equals(prefixNo)
                            || "QTRK".equals(prefixNo) || "DBCK".equals(prefixNo) || "ZZD".equals(prefixNo) || "CXD".equals(prefixNo)
                            || "PDLR".equals(prefixNo) || "PDFP".equals(prefixNo)|| "XDCG".equals(prefixNo)) {
                        //是否有对当前供应商的采购记录 有-取最近一条当前商品的单价
                        mvo.setTaxUnitPrice(mvo.getPurchaseDecimal());
                        mvo.setBillPrice(mvo.getPurchaseDecimal());
//                        if (!StringUtils.isEmpty(organId)){
//                            //采购价
//                            BigDecimal recentPurchase = depotItemService.getItemByHeaderIdAndBarcode(mvo.getMeId(), organId,mvo.getId());
//                            if (null !=recentPurchase && recentPurchase.compareTo(BigDecimal.ZERO)>0){
//                                mvo.setTaxUnitPrice(recentPurchase);
//                                mvo.setBillPrice(recentPurchase);
//                                mvo.setPriceNote("最近采购价");
//                            }else {
//                                mvo.setBillPrice(mvo.getPurchaseDecimal());
//                            }
//                        }else {
//                            mvo.setBillPrice(mvo.getPurchaseDecimal());
//                        }
                    } else if ("XSDD".equals(prefixNo) || "XSCK".equals(prefixNo) || "XSTH".equals(prefixNo) || "QTCK".equals(prefixNo) ||"PSD".equals(prefixNo) ||"CJZF".equals(prefixNo) ){
                        //销售价
                        //促销活动
                        mvo.setOriginalUnitPrice(mvo.getWholesaleDecimal());
                        Integer custom11=null;
                        if ("XSDD".equals(prefixNo) || "CJZF".equals(prefixNo)){
                            custom11=3;
                        }
                        if (custom11 !=null){
                            PromotionVoDetail head =null;
                            if (StringUtil.isNotEmpty(organId)){
                                head = promotionHeadService.checkMaterialWithCodeExist(mvo.getId(), mvo.getMeId(), mvo.getCommodityUnit(),1,null,custom11,organId);
                            }else {
                                head = promotionHeadService.checkMaterialWithCodeExist(mvo.getId(), mvo.getMeId(), mvo.getCommodityUnit(),1,1,custom11,null);
                            }
                            if (head != null) {
                                mvo.setTaxUnitPrice(head.getSpecialPrice());
                                mvo.setBillPrice(head.getSpecialPrice());
                                mvo.setPriceNote("zh".equals(lanCode) ? "促销价":"PEK-YVR");
                            }else {
                                mvo.setBillPrice(mvo.getWholesaleDecimal());
                            }
                        }else {
                            mvo.setBillPrice(mvo.getWholesaleDecimal());
                        }
                    }else if ("CXTJ".equals(prefixNo)){
                        mvo.setTaxUnitPrice(mvo.getWholesaleDecimal());
                        mvo.setBillPrice(mvo.getWholesaleDecimal());
                    }
//                    //仓库id
//                    if (depotId == null) {
//                        JSONArray depotArr = depotService.findDepotByCurrentUser();
//                        for (Object obj : depotArr) {
//                            JSONObject depotObj = JSONObject.parseObject(obj.toString());
//                            if (depotObj.get("isDefault") != null) {
//                                Boolean isDefault = depotObj.getBoolean("isDefault");
//                                if (isDefault) {
//                                    String id = depotObj.getString("id");
//                                    if (!"CGDD".equals(prefixNo) && !"XSDD".equals(prefixNo) && !"CXTJ".equals(prefixNo)) {
//                                        //除订单之外的单据才有仓库
//                                        mvo.setDepotId(id);
//                                    }
//                                    getStockByMaterialInfo(mvo);
//                                }
//                            }
//                        }
//                    } else {
//                        mvo.setDepotId(depotId);
//                        getStockByMaterialInfo(mvo);
//                    }
                }
            }
            res.code = 200;
            res.data = list;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
    /**
     * 根据商品id查询商品信息
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getMaterialByBarCode")
    @ApiOperation(value = "根据商品id查询商品信息")
    public BaseResponseInfo getMaterialByBarCode(@RequestParam("materialId")@ApiParam("商品id，用','号隔开") String materialId,
                                          @RequestParam(value = "depotId", required = false)@ApiParam("仓库 销售时，获取促销活动价") String depotId,
                                          @RequestParam(value = "organId", required = false)@ApiParam("客户id/供应商id  销售时，获取活动价、客户等级价") String organId,
                                          @RequestParam(required = false, value = "prefixNo")@ApiParam("单据前缀，如（促销特价：'CXTJ'）") String prefixNo,
                                          HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
        if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
            res.code = 500;
            res.data = "zh".equals(lanCode) ? "未设置税率" : "Untaxed rate";
            return res;
        }
        BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());
        try {
//            List<MaterialVo4Unit> list = materialService.getMaterialByMaterialId(materialId,prefixNo);
            List<MaterialVo4Unit> list = materialService.getMaterialByMaterialId(materialId,request,lanCode);
            if(list!=null && list.size()>0) {
                Map<String,BigDecimal> currentStockMap = materialService.getCurrentStockMapByIdListWithTenantId(list,depotId);
                for(MaterialVo4Unit mvo: list) {
                    //获取库存
                    BigDecimal stock = currentStockMap.get(mvo.getId())!=null? currentStockMap.get(mvo.getId()): BigDecimal.ZERO;
                    mvo.setStock(stock);
                    mvo.setDepotId(depotId);
                    mvo.setTaxRate(taxRate);
                    if ("LSCK".equals(prefixNo) || "LSTH".equals(prefixNo)) {
                        //零售价
                        mvo.setTaxUnitPrice(mvo.getCommodityDecimal());
                        mvo.setBillPrice(mvo.getCommodityDecimal());
                        mvo.setOriginalUnitPrice(mvo.getCommodityDecimal());
                    } else if ("CGDD".equals(prefixNo) || "CGRK".equals(prefixNo) || "CGTH".equals(prefixNo)
                            || "QTRK".equals(prefixNo) || "DBCK".equals(prefixNo) || "ZZD".equals(prefixNo) || "CXD".equals(prefixNo)
                            || "PDLR".equals(prefixNo) || "PDFP".equals(prefixNo)|| "XDCG".equals(prefixNo)|| "QCKC".equals(prefixNo)) {
                        //采购价
                        mvo.setTaxUnitPrice(mvo.getPurchaseDecimal());
                        mvo.setBillPrice(mvo.getPurchaseDecimal());
                    } else if ("XSDD".equals(prefixNo) || "XSCK".equals(prefixNo) || "XSTH".equals(prefixNo) || "QTCK".equals(prefixNo) ||"PSD".equals(prefixNo) ||"CJZF".equals(prefixNo) ){
                        //销售价
                        //促销活动
                        mvo.setOriginalUnitPrice(mvo.getWholesaleDecimal());
                        Integer custom11=null;
                        if ("XSDD".equals(prefixNo) || "CJZF".equals(prefixNo)){
                            custom11=3;
                        }
                        if (custom11 !=null){
                            PromotionVoDetail head =null;
                            if (StringUtil.isNotEmpty(organId)){
                                head = promotionHeadService.checkMaterialWithCodeExist(mvo.getId(), mvo.getMeId(), mvo.getCommodityUnit(),1,null,custom11,organId);
                            }else {
                                head = promotionHeadService.checkMaterialWithCodeExist(mvo.getId(), mvo.getMeId(), mvo.getCommodityUnit(),1,1,custom11,null);
                            }
                            if (head != null) {
                                mvo.setTaxUnitPrice(head.getSpecialPrice());
                                mvo.setBillPrice(head.getSpecialPrice());
                                mvo.setPriceNote("zh".equals(lanCode) ? "促销价":"PEK-YVR");
                            }else {
                                mvo.setBillPrice(mvo.getWholesaleDecimal());
                            }
                        }else {
                            mvo.setBillPrice(mvo.getWholesaleDecimal());
                        }
                    }else if ("CXTJ".equals(prefixNo)){
                            mvo.setBillPrice(mvo.getWholesaleDecimal());
                    }

//                    //仓库id
//                    if (depotId == null) {
//                        JSONArray depotArr = depotService.findDepotByCurrentUser();
//                        for (Object obj : depotArr) {
//                            JSONObject depotObj = JSONObject.parseObject(obj.toString());
//                            if (depotObj.get("isDefault") != null) {
//                                Boolean isDefault = depotObj.getBoolean("isDefault");
//                                if (isDefault) {
//                                    String id = depotObj.getString("id");
//                                    if (!"CGDD".equals(prefixNo) && !"XSDD".equals(prefixNo) && !"CXTJ".equals(prefixNo)
//                                            && !"CJZF".equals(prefixNo)&& !"ZFCJBJ".equals(prefixNo)&& !"CJBJ".equals(prefixNo)) {
//                                        //除订单之外的单据才有仓库
//                                        mvo.setDepotId(id);
//                                    }
//                                    getStockByMaterialInfo(mvo);
//                                }
//                            }
//                        }
//                    } else {
//                        mvo.setDepotId(depotId);
//                        getStockByMaterialInfo(mvo);
//                    }
                }
            }
            res.code = 200;
            res.data = list;
        } catch (BusinessRunTimeException e){
            res.code = e.getCode();
            res.data = e.getMessage();
        }catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    @GetMapping(value = "/getPriceByBarCode")
    @ApiOperation(value = "根据商品价格id查询商品信息")
    public BaseResponseInfo getPriceByBarCode(@RequestParam("meId")@ApiParam("商品价格id，用','号隔开") String meId,
                                                 @RequestParam(value = "grade", required = false)@ApiParam("等级，1-一级批发价\n" +
                                                         "2-二级批发价\n" +
                                                         "3-三级批发价\n" +
                                                         "4-四级批发价\n" +
                                                         "5-五级批发价\n" +
                                                         "6-零售价\n" +
                                                         "7-最低销售价") String grade,
                                                 HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        JSONArray dataArray = new JSONArray();
        try {
            List<MaterialVo4Unit> list = materialService.getMaterialByMeIdList(meId);
            if(list!=null && list.size()>0) {
                for(MaterialVo4Unit mvo: list) {
                    JSONObject map = new JSONObject();
                    map.put("barCode",mvo.getmBarCode());
                    map.put("meId",mvo.getMeId());
                        if (StringUtils.isEmpty(grade)){
                            mvo.setBillPrice(mvo.getWholesaleDecimal());
                            map.put("billPrice",mvo.getWholesaleDecimal());
                        }else {
                            switch (grade){
                                case "1":
                                    map.put("billPrice",mvo.getWholesaleDecimal());
                                    break;
                                case "2":
                                    map.put("billPrice",mvo.getTwoWholesaleDecimal());
                                    break;
                                case "3":
                                    map.put("billPrice",mvo.getThreeWholesaleDecimal());
                                    break;
                                case "4":
                                    map.put("billPrice",mvo.getFourWholesaleDecimal());
                                    break;
                                case "5":
                                    map.put("billPrice",mvo.getFiveWholesaleDecimal());
                                    break;
                                case "6":
                                    map.put("billPrice",mvo.getCommodityDecimal());
                                    break;
                                case "7":
                                    map.put("billPrice",mvo.getLowDecimal());
                                    break;

                            }
                        }
                    dataArray.add(map);
                }
            }
            res.code = 200;
            res.data = dataArray;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
    * @Author: wy
    * @Description: 根据等级返回促销价
    * @DateTime: 2022/8/4 17:00
    * @Params:
    * @Return
    */
    private void getBillPriceByMvo(MaterialVo4Unit mvo,String grade,String supplierId){
        String lanCode = systemConfigService.getLanCode();
        switch (grade){
            case "1":
                mvo.setTaxUnitPrice(mvo.getWholesaleDecimal());
                mvo.setBillPrice(mvo.getWholesaleDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "一级批发价" :"Primary wholesale price");
                break;
            case "2":
                mvo.setTaxUnitPrice(mvo.getTwoWholesaleDecimal());
                mvo.setBillPrice(mvo.getTwoWholesaleDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "二级批发价" :"Secondary wholesale price");
                break;
            case "3":
                mvo.setTaxUnitPrice(mvo.getThreeWholesaleDecimal());
                mvo.setBillPrice(mvo.getThreeWholesaleDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "三级批发价":"Tertiary wholesale price");
                break;
            case "4":
                mvo.setTaxUnitPrice(mvo.getFourWholesaleDecimal());
                mvo.setBillPrice(mvo.getFourWholesaleDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "四级批发价":"Level 4 Wholesale Price");
                break;
            case "5":
                mvo.setTaxUnitPrice(mvo.getFiveWholesaleDecimal());
                mvo.setBillPrice(mvo.getFiveWholesaleDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "五级批发价":"Level 5 wholesale price");
                break;
            case "6":
                mvo.setTaxUnitPrice(mvo.getCommodityDecimal());
                mvo.setBillPrice(mvo.getCommodityDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "零售价":"retail price");
                break;
            case "7":
                mvo.setTaxUnitPrice(mvo.getLowDecimal());
                mvo.setBillPrice(mvo.getLowDecimal());
                mvo.setPriceNote("zh".equals(lanCode) ? "最低销售价":"Minimum selling price");
                break;
             case "8":
                 BigDecimal lastSellingPrice = depotItemService.getItemByBarcode(mvo.getMeId(), supplierId, mvo.getId());
                 mvo.setBillPrice(lastSellingPrice);
                 mvo.setTaxUnitPrice(lastSellingPrice);
                 mvo.setPriceNote("zh".equals(lanCode) ? "本客户最新售价":"The latest price of this customer");
                break;
        }
    }

    private BigDecimal getSpecialPrice(){

        return  BigDecimal.ZERO;
    }
    /**
     * 根据商品信息获取库存，进行赋值
     * @param mvo
     * @throws Exception
     */
//    private void getStockByMaterialInfo(MaterialVo4Unit mvo) throws Exception {
//        BigDecimal stock;
//        if (StringUtil.isNotEmpty(mvo.getSku())) {
//            stock = depotItemService.getSkuStockByParam(mvo.getDepotId(), mvo.getMeId(), null, null);
//        } else {
//            stock = depotItemService.getStockByParam(mvo.getDepotId(), mvo.getId(), null, null);
//            if (mvo.getUnitId() != null) {
//                Unit unit = unitService.getUnit(mvo.getUnitId());
//                String commodityUnit = mvo.getCommodityUnit();
//                stock = unitService.parseStockByUnit(stock, unit, commodityUnit);
//            }
//        }
//        mvo.setStock(stock);
//    }

    /**
     * 商品库存查询
     * @param currentPage
     * @param pageSize
     * @param depotIds
     * @param categoryId
     * @param materialParam
     * @param mpList
     * @param column
     * @param order
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getListWithStock")
    @ApiOperation(value = "商品库存查询")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取列表",response = Material.class)
    })
    public BaseResponseInfo getListWithStock(@RequestParam("currentPage") Integer currentPage,
                                             @RequestParam("pageSize") Integer pageSize,
                                             @RequestParam(value = "depotIds", required = false) String depotIds,
                                             @RequestParam(value = "categoryId", required = false) String categoryId,
                                             @RequestParam("materialParam") String materialParam,
                                             @RequestParam("zeroStock") Integer zeroStock,
                                             @RequestParam("mpList") String mpList,
                                             @RequestParam("column") String column,
                                             @RequestParam("order") String order,
                                             HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        Map<String, Object> map = new HashMap<>();
        try {
            List<String> idList = new ArrayList<>();
            List<String> depotList = new ArrayList<>();
            List<String> tenantIdList = new ArrayList<>();
            if(StringUtil.isNotEmpty(categoryId)){
                idList = materialService.getListByParentId(categoryId);
            }
            if(StringUtil.isNotEmpty(depotIds)) {
                depotList = StringUtil.strToStringList(depotIds);
            }else {
                //未选择仓库时默认为当前用户有权限的仓库
                JSONArray depotArr = depotService.findDepotByCurrentUser();
                for(Object obj: depotArr) {
                    JSONObject object = JSONObject.parseObject(obj.toString());
                    depotList.add(object.getString("id"));
                }
            }

            tenantIdList=materialService.getTenantIdListByDepotIdList(depotList);
            Map<String, BigDecimal> initialStockMap = new HashMap<>();
            List<MaterialInitialStockWithMaterial> initialStockList = materialService.getInitialStockWithMaterial(depotList,tenantIdList);
            for (MaterialInitialStockWithMaterial mism: initialStockList) {
                initialStockMap.put(mism.getMaterialId(), mism.getNumber());
            }
            List<MaterialVo4Unit> dataList = materialService.getListWithStock(depotList, idList, StringUtil.toNull(materialParam), zeroStock,
                    StringUtil.safeSqlParse(column), StringUtil.safeSqlParse(order), (currentPage-1)*pageSize, pageSize,tenantIdList);
            int total = materialService.getListWithStockCount(depotList, idList, StringUtil.toNull(materialParam), zeroStock,tenantIdList);
            MaterialVo4Unit materialVo4Unit= materialService.getTotalStockAndPrice(depotList, idList, StringUtil.toNull(materialParam),tenantIdList);
            map.put("total", total);
            map.put("currentStock", materialVo4Unit.getCurrentStock());
            map.put("currentStockPrice", materialVo4Unit.getCurrentStockPrice());
            for(MaterialVo4Unit item: dataList) {
                item.setInitialStock(initialStockMap.get(item.getId()));
            }
            map.put("rows", dataList);
            res.code = 200;
            res.data = map;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 批量设置商品当前的实时库存（按每个仓库）
     * @param jsonObject
     * @param request
     * @return
     * @throws Exception
     */
//    @PostMapping(value = "/batchSetMaterialCurrentStock")
//    @ApiOperation(value = "批量设置商品当前的实时库存（按每个仓库）")
//    public String batchSetMaterialCurrentStock(@RequestBody JSONObject jsonObject,
//                                 HttpServletRequest request)throws Exception {
//        String ids = jsonObject.getString("ids");
//        Map<String, Object> objectMap = new HashMap<>();
//        String lanCode = redisService.getLanCodeFromSession(request);
//        int res = materialService.batchSetMaterialCurrentStock(ids);
//        if(res > 0) {
//            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
//        } else {
//            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
//        }
//    }

    /**
     * 批量更新商品信息
     * @param jsonObject
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/batchUpdate")
    @ApiOperation(value = "批量更新商品信息")
    public String batchUpdate(@RequestBody JSONObject jsonObject,
                              HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        int res = materialService.batchUpdate(jsonObject);
        String lanCode = redisService.getLanCodeFromSession(request);
        if(res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    @GetMapping(value = "/posMaterialList")
    @ApiOperation(value = "零售商品列表")
    public Object posMaterialList(HttpServletRequest request)throws Exception {
        Map<String,Object> map = new HashMap<>();
        List<PosMaterialVo> list = materialService.posMaterialList();
        map.put("status",1);
        map.put("limit",500);
        map.put("data",list);
        map.put("size",list.size());
        return map;
    }

    @GetMapping(value = "/posSaleMaterialList")
    @ApiOperation(value = "仓库零售商品列表")
    public Object posSaleMaterialList(HttpServletRequest request)throws Exception {
        Map<String,Object> map = new HashMap<>();
        List<PosMaterialVo> list = materialService.posSaleMaterialList();
        map.put("status",1);
        map.put("limit",500);
        map.put("data",list);
        map.put("size",list.size());
        return map;
    }

    @GetMapping(value = "/balanceMaterialList")
    @ApiOperation(value = "传秤商品列表")
    public Object balanceMaterialList(
            @RequestParam String pricing_method,@RequestParam String keyword,
            @RequestParam String attribute_state,@RequestParam String person1,
            @RequestParam String person2,@RequestParam String person3,
            @RequestParam Integer page,@RequestParam Integer limit,
            HttpServletRequest request)throws Exception {
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        List<BalanceMaterialVo> list = materialService.balanceMaterialList(pricing_method,keyword,person1,person2,person3,(page - 1) * limit,limit);
        map.put("status",1);
        map.put("message","获取成功");
        data.put("list",list);
        data.put("count",list.size());
        map.put("data",data);
        return map;
    }

    @PostMapping(value = "/updatePluCode")
    @ApiOperation(value = "传秤商品列表")
    public Object updatePluCode(@RequestBody JSONObject jsonObject,
                                HttpServletRequest request)throws Exception {
        Map<String,Object> map = materialService.updatePluCode(jsonObject);
        return map;
    }

    @GetMapping(value = "/goodsSort")
    @ApiOperation(value = "商品类型列表")
    public Object goodsSort(@RequestParam String id,
            HttpServletRequest request)throws Exception {
        Map<String,Object> map = materialService.goodsSort(id);
        return map;
    }


    @PostMapping(value = "/DHChuancheng")
    @ApiOperation(value = "大华传秤")
    public Object DHChuancheng(@RequestBody JSONObject jsonObject,
                                HttpServletRequest request)throws Exception {

        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isNotEmpty(jsonObject.getString("str")) && StringUtils.isNotEmpty(jsonObject.getString("ip"))){
            SocketUtils socketUtils = new SocketUtils();
            socketUtils.connect(jsonObject.getString("ip"));
            boolean b = socketUtils.setGoods(jsonObject.getString("str"));
            if (b){
                map.put("status",1);
            }else {
                map.put("status",0);
            }
            socketUtils.closeConnect();
        }else {
            map.put("status",0);
        }
        return map;
    }


    @PostMapping(value = "/batchUpdatePrice")
    @ApiOperation(value = "批量修改价格")
    public Object batchUpdatePrice(@RequestBody BatchUpdatePriceVo vo,
                               HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        materialService.batchUpdatePrice(vo);
        res.code = 200;
        return res;
    }


    @PostMapping(value = "/batchSetMaterialTenant")
    @ApiOperation(value = "批量设置商品下发的租户")
    public String batchSetMaterialTenant(@RequestBody JSONObject jsonObject,
                                               HttpServletRequest request)throws Exception {
        String ids = jsonObject.getString("ids");
        String syncTenantId = jsonObject.getString("syncTenantId");
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        int res = materialService.batchSetMaterialTenant(ids,syncTenantId);
        if(res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/batchUpdateStock")
    @ApiOperation(value = "库存重新统计")
    public String batchUpdateStock(@RequestBody JSONObject jsonObject,
                                HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String token = request.getHeader("X-Access-Token");
        String tenantId = Tools.getTenantIdByToken(token);
        if (StringUtil.isEmpty(tenantId) || "0".equals(tenantId)){
            returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.UPDATE_STOCK_FAILED.name : ErpInfo.UPDATE_STOCK_FAILED.lanCodeName, ErpInfo.UPDATE_STOCK_FAILED.code);
        }
        materialService.batchUpdateStock(jsonObject);
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @PostMapping(value = "/saveStockHistory")
    @ApiOperation(value = "保存当前库存")
    public String saveStockHistory(@RequestBody JSONObject jsonObject,
                                   HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String token = request.getHeader("X-Access-Token");
        String tenantId = Tools.getTenantIdByToken(token);
        if (StringUtil.isEmpty(tenantId) || "0".equals(tenantId)){
            returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.UPDATE_STOCK_FAILED.name : ErpInfo.UPDATE_STOCK_FAILED.lanCodeName, ErpInfo.UPDATE_STOCK_FAILED.code);
        }
        materialService.saveStockHistory(jsonObject);
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }
}
